from typing import Dict, Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from pydantic import BaseModel, validator
from app.database.connection import get_db
from app.services.chat_service import chat_manager
from app.models.user import User
from app.routers.auth import get_current_user
import logging

# 配置日志
logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter(prefix="/chat", tags=["AI对话"])

# HTTP Bearer 认证
security = HTTPBearer()

# Pydantic 模型
class ChatMessage(BaseModel):
    """聊天消息模型"""
    message: str
    session_id: Optional[int] = None
    enable_search: bool = False
    enable_personalization: bool = False
    enable_deep_thinking: bool = False
    search_engine: str = "tavily"
    
    @validator('message')
    def message_must_not_be_empty(cls, v):
        if not v or not v.strip():
            raise ValueError('消息内容不能为空')
        if len(v.strip()) > 2000:
            raise ValueError('消息内容不能超过2000字符')
        return v.strip()
    
    @validator('search_engine')
    def search_engine_validation(cls, v):
        allowed_engines = ["tavily"]
        if v not in allowed_engines:
            raise ValueError(f'搜索引擎必须是以下之一: {", ".join(allowed_engines)}')
        return v

class SessionCreateRequest(BaseModel):
    session_title: Optional[str] = None

class SessionRenameRequest(BaseModel):
    new_title: str

class ChatResponse(BaseModel):
    """聊天响应模型"""
    response: str
    timestamp: str
    search_used: bool
    personalization_used: bool
    deep_thinking_used: bool
    search_engine: Optional[str] = None
    user_id: str
    user_intent: Optional[str] = None  # 用户意图
    specialized_mode: Optional[str] = None  # 专业模式名称
    session_id: Optional[int] = None

class ChatHistoryResponse(BaseModel):
    """聊天历史响应模型"""
    user_id: str
    history: List[Dict[str, Any]]
    total_messages: int

class ChatClearResponse(BaseModel):
    """清空聊天历史响应模型"""
    user_id: str
    message: str
    success: bool

# API 路由
@router.post("/message", response_model=ChatResponse, summary="发送聊天消息")
async def send_chat_message(
    chat_data: ChatMessage,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """发送聊天消息并获取AI响应"""
    try:
        user_id = str(current_user.id)
        logger.info(f"用户 {user_id} 发送消息: {chat_data.message[:50]}...")
        
        # 调用聊天管理器处理消息
        result = chat_manager.process_chat_message(
            user_id=user_id,
            message=chat_data.message,
            session_id=chat_data.session_id,
            enable_search=chat_data.enable_search,
            enable_personalization=chat_data.enable_personalization,
            enable_deep_thinking=chat_data.enable_deep_thinking,
            search_engine=chat_data.search_engine,
            db=db
        )
        
        logger.info(f"用户 {user_id} 消息处理成功，搜索使用: {result.get('search_used', False)}")
        
        return ChatResponse(
            response=result["response"],
            timestamp=result["timestamp"],
            search_used=result.get("search_used", False),
            personalization_used=result.get("personalization_used", False),
            deep_thinking_used=result.get("deep_thinking_used", False),
            search_engine=result.get("search_engine"),
            user_id=user_id,
            user_intent=result.get("user_intent"),
            specialized_mode=result.get("specialized_mode"),
            session_id=result.get("session_id")
        )
        
    except Exception as e:
        logger.error(f"用户 {current_user.id} 聊天消息处理异常: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"消息处理失败: {str(e)}"
        )

@router.get("/history", response_model=ChatHistoryResponse, summary="获取聊天历史")
async def get_chat_history(
    session_id: Optional[int] = None,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的聊天历史"""
    try:
        user_id = str(current_user.id)
        logger.info(f"获取用户 {user_id} 的聊天历史")
        
        # 获取聊天历史
        history = chat_manager.get_chat_history(user_id, session_id, db)
        
        logger.info(f"用户 {user_id} 聊天历史获取成功，共 {len(history)} 条消息")
        
        return ChatHistoryResponse(
            user_id=user_id,
            history=history,
            total_messages=len(history)
        )
        
    except Exception as e:
        logger.error(f"用户 {current_user.id} 获取聊天历史异常: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取聊天历史失败: {str(e)}"
        )

@router.delete("/history", response_model=ChatClearResponse, summary="清空聊天历史")
async def clear_chat_history(
    session_id: Optional[int] = None,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """清空当前用户的聊天历史"""
    try:
        user_id = str(current_user.id)
        logger.info(f"清空用户 {user_id} 的聊天历史")
        
        # 清空聊天历史
        chat_manager.clear_chat_history(user_id, session_id, db)
        
        logger.info(f"用户 {user_id} 聊天历史清空成功")
        
        return ChatClearResponse(
            user_id=user_id,
            message="聊天历史已清空",
            success=True
        )
        
    except Exception as e:
        logger.error(f"用户 {current_user.id} 清空聊天历史异常: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"清空聊天历史失败: {str(e)}"
        )

@router.get("/status", summary="获取聊天服务状态")
async def get_chat_status(
    current_user: User = Depends(get_current_user)
):
    """获取聊天服务状态信息"""
    try:
        logger.info(f"用户 {current_user.id} 获取聊天服务状态")
        
        return {
            "status": "active",
            "message": "聊天服务运行正常",
            "supported_features": {
                "search": True,
                "personalization": True,
                "deep_thinking": True
            },
            "supported_engines": ["tavily"]
        }
        
    except Exception as e:
        logger.error(f"用户 {current_user.id} 获取聊天服务状态异常: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取服务状态失败: {str(e)}"
        )

# 会话管理API
@router.post("/sessions", summary="创建新会话")
async def create_session(
    request: SessionCreateRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新的聊天会话"""
    try:
        user_id = str(current_user.id)
        result = chat_manager.create_session(user_id, request.session_title, db)
        return result
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建会话失败: {str(e)}"
        )

@router.get("/sessions", summary="获取用户会话列表")
async def get_sessions(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户的所有会话"""
    try:
        user_id = str(current_user.id)
        sessions = chat_manager.get_user_sessions(user_id, db)
        return {"success": True, "sessions": sessions}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取会话列表失败: {str(e)}"
        )

@router.put("/sessions/{session_id}", summary="重命名会话")
async def rename_session(
    session_id: int,
    request: SessionRenameRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """重命名会话"""
    try:
        user_id = str(current_user.id)
        result = chat_manager.rename_session(user_id, session_id, request.new_title, db)
        return result
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"重命名会话失败: {str(e)}"
        )

@router.delete("/sessions/{session_id}", summary="删除会话")
async def delete_session(
    session_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除会话"""
    try:
        user_id = str(current_user.id)
        result = chat_manager.delete_session(user_id, session_id, db)
        return result
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除会话失败: {str(e)}"
        )

@router.get("/sessions/{session_id}", summary="获取会话信息")
async def get_session_info(
    session_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取会话信息"""
    try:
        user_id = str(current_user.id)
        result = chat_manager.get_session_info(user_id, session_id, db)
        return result
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取会话信息失败: {str(e)}"
        )